package com.chenjim.architecture.screen

import android.os.SystemClock
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.chenjim.architecture.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Preview
@Composable
fun SplashScreenPreview() {
    SplashScreen(navController = rememberNavController())
}

@Composable
fun SplashScreen(
    navController: NavHostController,
    viewModel: SplashScreenVM = hiltViewModel()
) {
    LaunchedEffect(Unit) {
        launch(Dispatchers.Main) {
            SystemClock.sleep(1000)
            navController.popBackStack()
            if (viewModel.dateStore.isLoggedIn()) {
                navController.navigate(Screen.Home.route)
            } else {
                navController.navigate(Screen.Login.route)
            }

        }
    }
    Box(
        modifier = Modifier
            .fillMaxSize(), contentAlignment = Alignment.Center
    ) {
        Image(
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop,
            painter = painterResource(R.drawable.splash), contentDescription = ""
        )
    }
}
